<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/29
 * Time: 15:23
 */

namespace app\api\controller\android\v12;


use think\Controller;
use think\Exception;
use think\Request;
use  app\api\model\OrderModel;
use app\api\model\PollingModel;
use app\api\model\Authority;
use redis\RedisPackage;
use  app\api\model\Approval;

class LargeConstruction extends Controller
{
    protected $us;

    public function _initialize()
    {
        $this->us = Authority::check(1);
    }

    public function getList()
    {
        $param      = Request::instance()->get();
        $acceptanc  = \db('large_construction_acceptance', config('database.zong'))->where('whole', 1)->field('count(order_id) as count,order_id')->group('order_id')
            ->buildSql();
        $fieldCount = \db('large_construction_field', config('database.zong'))->where('enable', 0)->where('pid', '<>', 0)->count();
        $list       = \db('order', config('database.zong'))
//            ->Join(config('database')['database'] . '.envelopes', 'envelopes.ordesr_id=order.order_id and envelopes.type=1', 'left')
            ->Join('order_info', 'order.order_id=order_info.order_id', 'left');
        if ($param['type'] == 2) {
            $list->Join([$acceptanc => 'acceptance'], 'acceptance.order_id=order.order_id', 'left')
                ->where('acceptance.count', $fieldCount);
        }else{
            $list->Join([$acceptanc => 'acceptance'], 'acceptance.order_id=order.order_id', 'left')
                ->where(function ($quer) use ($fieldCount){
                    $quer->where('acceptance.count','<>', $fieldCount) ->whereOr('acceptance.count','EXP','IS NULL');
                });

        }

        $list = $list->where('order_info.gong', '>=', 30)
            ->whereBetween('order.state', [4, 7])
            ->where('order.assignor', $this->us['user_id'])
            ->whereNull('order.cleared_time')
            ->whereNull('order.acceptance_time')
            ->field('concat(order_info.province,order_info.city,order_info.county,order.addres) as  addres,FROM_UNIXTIME(order.start_time,"%Y-%m-%d %H:%i:%s") as start_time,order_info.gong,order.state,order.order_id,order.contacts,order.telephone,datediff(NOW(),FROM_UNIXTIME(order.start_time,"%Y-%m-%d %H:%i:%s")) as day,order_info.pro_id_title')
            ->page($param['page'], $param['limit'])
            ->select();

        $count = \db('order', config('database.zong'))
//            ->Join(config('database')['database'] . '.envelopes', 'envelopes.ordesr_id=order.order_id and envelopes.type=1', 'left')
            ->Join('order_info', 'order.order_id=order_info.order_id', 'left');

        if ($param['type'] == 2) {
            $count->Join([$acceptanc => 'acceptance'], 'acceptance.order_id=order.order_id', 'left')
                ->where('acceptance.count', $fieldCount);
        }else{
            $count->Join([$acceptanc => 'acceptance'], 'acceptance.order_id=order.order_id', 'left')
                ->where(function ($quer) use ($fieldCount){
                    $quer->where('acceptance.count','<>', $fieldCount) ->whereOr('acceptance.count','EXP','IS NULL');
                });
        }
        $count = $count->where('order_info.gong', '>=', 30)
            ->whereBetween('order.state', [4, 7])
            ->where('order.assignor', $this->us['user_id'])
            ->whereNull('order.cleared_time')
            ->whereNull('order.acceptance_time')
            ->count();
        r_date(['list' => $list, 'count' => $count], 200);
    }

    public function getInfo()
    {
        $param = Request::instance()->get();
        $list  = \db('order')
            ->Join('province', 'order.province_id=province.province_id', 'left')
            ->Join('city', 'order.city_id=city.city_id', 'left')
            ->Join('goods_category', 'order.pro_id=goods_category.id', 'left')
            ->Join('county', 'order.county_id=county.county_id')
            ->field('concat(province.province,city.city,county.county,order.addres) as  addres,concat(order.contacts,"(",order.telephone,")" ) as contacts,goods_category.title')
            ->where('order.order_id', $param['order_id'])
            ->find();

        $rows = \db('large_construction_field', config('database.zong'))->where('enable', 0)->where('pid', 0)->order('sort asc')->field('id,title,type')->select();

        foreach ($rows as $k => $l) {
            $fieldCount = \db('large_construction_field', config('database.zong'))->where('enable', 0)->where('pid', $l['id'])->column('id');

            $acceptance = \db('large_construction_acceptance', config('database.zong'))->where('type', $l['type'])->whereIn('working_procedure', $fieldCount)->where('order_id', $param['order_id'])->where(function ($quer) {
                $quer->where('result', 1)->whereOr('result', 3)->whereOr('result', 4);
            })->count();

            if (count($fieldCount) == $acceptance) {
                $rows[$k]['check'] = 1;
            } else {
                $rows[$k]['check'] = 0;
            }
        }

        r_date(['data' => $list, 'largeConstruction' => $rows], 200);

    }

    /*
     * 不验收此工地
     */
    public function NonAcceptance()
    {
        $param                = Request::instance()->post();
        $workingProcedure     = json_decode($param['workingProcedure'], true);
        $type_of_work         = \db('large_construction_field', config('database.zong'))->where('type', $param['type'])->value('type_of_work');
        $workingProcedureList = \db('large_construction_field', config('database.zong'))->whereIn('id', $workingProcedure)->field('id,title')->select();
        foreach ($workingProcedureList as $list) {
            \db('large_construction_acceptance', config('database.zong'))->insert([
                'order_id' => $param['order_id'],
                'type' => $param['type'],
                'type_of_work' => $type_of_work,
                'result' => 4,
                'remarks' => '',
                'picture' => '',
                'working_procedure' => $list['id'],
                'working_procedure_title' => $list['title'],
                'created_time' => time(),
                'whole' => 1
            ]);
        }
        r_date(null, 200);
    }

    public function add()
    {
        $param                 = Request::instance()->post();
        $type_of_work          = \db('large_construction_field', config('database.zong'))->where('type', $param['type'])->value('type_of_work');
        $workingProcedureTitle = \db('large_construction_field', config('database.zong'))->where('id', $param['workingProcedure'])->value('title');
        $picture=json_decode($param['picture'], true);
        if (isset($param['id']) && $param['id'] != 0) {
            \db('large_construction_acceptance', config('database.zong'))->where('id', $param['id'])->update([
                'result' => $param['result'],
                'remarks' => $param['remarks'],
                'picture' => !empty($picture) ? serialize($picture) : '',
            ]);
        } else {
            \db('large_construction_acceptance', config('database.zong'))->insert([
                'order_id' => $param['order_id'],
                'type' => $param['type'],
                'type_of_work' => $type_of_work,
                'result' => $param['result'],
                'remarks' => $param['remarks'],
                'picture' => !empty($picture) ? serialize($picture) : '',
                'working_procedure' => $param['workingProcedure'],
                'working_procedure_title' => $workingProcedureTitle,
                'created_time' => time(),
            ]);
        }

        //总共有多少个验收项目
        $rows = \db('large_construction_field', config('database.zong'))->where('enable', 0)->where('type', $param['type'])->where('pid', '<>', 0)->count();


        //验收了多少个小巷
        $id = \db('large_construction_acceptance', config('database.zong'))->where(function ($quer) {
            $quer->where('result', 1)->whereOr('result', 3);
        })->where(['order_id' => $param['order_id']])->where('type', $param['type'])->count();

        if ($rows == $id) {
            \db('large_construction_acceptance', config('database.zong'))
                ->where(['order_id' => $param['order_id'], 'type' => $param['type']])
                ->update(['whole' => 1]);
        } else {
            \db('large_construction_acceptance', config('database.zong'))
                ->where(['order_id' => $param['order_id'], 'type' => $param['type']])
                ->update(['whole' => 0]);
        }
        r_date(null, 200);

    }

    public function EchoData()
    {
        $param                 = Request::instance()->get();
        $acceptance            = \db('large_construction_acceptance', config('database.zong'))->where('working_procedure', $param['id'])->where('order_id',$param['order_id'])->field('result,remarks,picture,working_procedure_title,id')->find();
        $acceptance['picture'] = empty($acceptance['picture']) ? [] : unserialize($acceptance['picture']);
        r_date($acceptance, 200);

    }

    public function getInfoList()
    {
        $param = Request::instance()->get();

        $rows = \db('large_construction_field', config('database.zong'))
            ->join('large_construction_acceptance', 'large_construction_acceptance.working_procedure=large_construction_field.id and large_construction_acceptance.order_id=' . $param['order_id'], 'left')
            ->where('enable', 0)
            ->where('large_construction_field.pid', $param['id'])
            ->order('sort asc')
            ->field('large_construction_field.id,large_construction_field.title,ifNULL(large_construction_acceptance.result,0) as result')->select();

        r_date($rows, 200);

    }

    /*
     * 二维码
     */
    public function QrCode()
    {
        $param = Request::instance()->get();
        $qc    = json_decode(qrcode($param['order_id']), true);
        if ($qc['success']) {
            $redis         = new RedisPackage();
            $redis::set('clock_in_addres_' . $param['order_id'],json_encode(['lat'=>$param['lat'],'lng'=>$param['lng'],'address'=>$param['address']]),1800);
            $data = $qc['obj'];
            r_date($data, 200);
        }

        r_date(null, 300, '获取失败');

    }

    /*
     * 提前结算的工地
     */
    public function advance()
    {
        $param     = Request::instance()->get();
        $acceptanc = \db('large_construction_examine', config('database.zong'))->where('state', 1)->where('type', '<>',99)->field('count(order_id) as count,order_id')->group('order_id')
            ->buildSql();

        $partAcceptanc = \db('large_construction_acceptance', config('database.zong'))->where('whole', 1)->where('type', '<>',99)->field('count(order_id) as count,order_id')->group('order_id')->buildSql();
//        $count1         = \db('large_construction_acceptance', config('database.zong'))->where('result', 1)->count();

        $list = \db('order', config('database.zong'))
//            ->Join(config('database')['database'] . '.envelopes', 'envelopes.ordesr_id=order.order_id and envelopes.type=1', 'left')
            ->Join('order_info', 'order.order_id=order_info.order_id', 'left');
        if ($param['type'] == 1) {
            $list->Join([$partAcceptanc => 'partAcceptanc'], 'partAcceptanc.order_id=order.order_id ', 'left')
                ->where('partAcceptanc.count', '>', 0)
                ->whereNull('order.cleared_time');
        } else {

            $list->Join([$acceptanc => 'examine'], 'examine.order_id=order.order_id ', 'left')
                ->where('examine.count', '>',0);
        }
        $list = $list->where('order_info.gong', '>=', 30)
            ->whereBetween('order.state', [4, 7])
            ->where('order.assignor', $this->us['user_id'])

            ->field('concat(order_info.province,order_info.city,order_info.county,order.addres) as  addres,FROM_UNIXTIME(order.start_time,"%Y-%m-%d %H:%i:%s") as start_time,order_info.gong,order.state,order.order_id,order.contacts,order.telephone,datediff(NOW(),FROM_UNIXTIME(order.start_time,"%Y-%m-%d %H:%i:%s")) as day,order_info.pro_id_title')
            ->page($param['page'], $param['limit'])
            ->select();

        $count = \db('order', config('database.zong'))
//            ->Join(config('database')['database'] . '.envelopes', 'envelopes.ordesr_id=order.order_id and envelopes.type=1', 'left')
            ->Join('order_info', 'order.order_id=order_info.order_id', 'left');

        if ($param['type'] == 1) {

            $count->Join([$partAcceptanc => 'partAcceptanc'], 'partAcceptanc.order_id=order.order_id ', 'left')
                ->where('partAcceptanc.count', '>', 0)
                ->whereNull('order.cleared_time');
        } else {

            $count->Join([$acceptanc => 'examine'], 'examine.order_id=order.order_id ', 'left')
                ->where('examine.count', '>',0);
        }

        $count = $count->where('order_info.gong', '>=', 30)
            ->whereBetween('order.state', [4, 7])
            ->where('order.assignor', $this->us['user_id'])


            ->count();
        r_date(['list' => $list, 'count' => $count], 200);
    }

    /*
     * 提前结算的工地
     */
    public function advanceInfo()
    {
        $param = Request::instance()->get();

        $list      = \db('order', config('database.zong'))
            ->Join('order_info', 'order.order_id=order_info.order_id', 'left')
            ->field('concat(order_info.province,order_info.city,order_info.county,order.addres) as  addres,concat(order.contacts,"(",order.telephone,")" ) as contacts,order_info.pro_id_title')
            ->where('order.order_id', $param['order_id'])
            ->find();
        $acceptanc = db('large_construction_acceptance', config('database.zong'))->where('order_id', $param['order_id'])->where('result', '<>', 4)->where('type', '<>', 99)->where('whole', 1)->group('type')->field('type,type_of_work as title,order_id,id')->select();

        foreach ($acceptanc as $k => $li) {
            $state = db('large_construction_examine', config('database.zong'))->where('order_id', $param['order_id'])->where('type', $li['type'])->order('id desc')->column('state');
            if ($state) {
                $acceptanc[$k]['state'] = $state[0];
            } else {
                $acceptanc[$k]['state'] = 0;
            }

        }

        r_date(['data' => $list, 'list' => $acceptanc], 200);
    }

    /*
     * 提前结算的工地
     */
    public function GetMaster()
    {
        $param = Request::instance()->get();

        $list = \db('app_user_order', config('database.db2'))
            ->join('app_user', 'app_user.id=app_user_order.user_id', 'left')
            ->whereNull('app_user_order.deleted_at')
            ->where('app_user_order.status', '<>', 10)
            ->where('app_user_order.order_id', $param['order_id'])
            ->where(function ($quer) use ($param) {
                $quer->where('app_user.work_type_id', $param['type'])->whereOr('app_user.work_type_id', 1);
            })
            ->field('app_user.username,app_user.id,app_user_order.order_id')
            ->select();

//        $title = \db('large_construction_field', config('database.zong'))->where('type', $param['type'])->value('type_of_work');
        r_date(['data' => $list], 200);
    }

    /*
     *  提前结算
     */
    public function EarlySettlement(Approval $approval)
    {
        $param = Request::instance()->post();
        db()->startTrans();
        try {
            $data = json_decode($param['list'], true);

            $sum = array_sum(array_column($data, 'money'));

            if ($param['amount'] * 0.8 < $sum) {
                throw new Exception('提前结算金额不能大于预计工费的80%');
            }

            $type_of_work = \db('large_construction_field', config('database.zong'))->where('type', $param['type'])->value('type_of_work');

            $user   = '';
            $idList = [];
            foreach ($data as $list) {
                $id = \db('large_construction_examine', config('database.zong'))->insertGetId([
                    'type' => $param['type'],// '对应工种id',
                    'type_of_work' => $type_of_work,//'对应工种名称',
                    'amount' => $param['amount'],//'预计总费用',
                    'master_id' => $list['id'],//'师傅id',
                    'advance_amount' => $list['money'],// '提前结算金额',
                    'order_id' => $param['order_id'],//,
                    'created_time' => time(), //'创建时间',
                    'state' => 3,//'0未提交1审核通过2拒绝3提交',

                ]);

                $user .= '师傅' . $list['username'] . '(提前结算工费：' . $list['money'] . ')';

                $idList[] = $id;
            }

            $approve = \db('large_construction_approve', config('database.zong'))->insertGetId(['order_id' => $param['order_id'], 'large_id' => implode($idList, ','), 'created_time' => time(), 'amount' => $param['amount'], 'type_of_work' => $type_of_work, 'type' => $param['type']]);
            $title   = $user . '提前结算工费';
            $approval->Reimbursement($approve, $title, $this->us['username'], 8);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());

        }

    }

    /*
     *  提前结算
     */
    public function EarlySettlementEchoData()
    {
        $param = Request::instance()->get();

        $type_of_work           = \db('large_construction_approve', config('database.zong'))
            ->join('approval', 'approval.relation_id=large_construction_approve.id and approval.type=7', 'left')
            ->join('bi_user', 'approval.nxt_id=bi_user.user_id', 'left')
            ->where('large_construction_approve.type', $param['type'])
            ->where('large_construction_approve.order_id', $param['order_id'])
            ->field('large_construction_approve.id,large_construction_approve.type_of_work,large_construction_approve.amount,large_construction_approve.large_id,ifNULL(FROM_UNIXTIME(approval.approved_time,"%Y-%m-%d %H:%i:%s"),"") as creation_time,bi_user.username')
            ->order('large_construction_approve.id desc')
            ->find();
        $acceptance             = \db('large_construction_examine', config('database.zong'))
            ->field('master_id,advance_amount,reason,state')
            ->whereIn('id', $type_of_work['large_id'])
            ->select();
        $type_of_work['reason'] = $acceptance[0]['reason'];
        $type_of_work['state']  = $acceptance[0]['state'];
        foreach ($acceptance as $k => $item) {
            $acceptance[$k]['username'] = \db('app_user', config('database.db2'))->where('id', $item['master_id'])->value('username');
            unset($acceptance[$k]['reason'], $acceptance[$k]['state']);
        }
        $type_of_work['data'] = $acceptance;

        r_date($type_of_work, 200);

    }

    /*
     * 上门打卡二维码通知
     */
    public function PunchInQRCode(\app\api\model\Common $common,OrderModel $orderModel)
    {

        $param         = Request::instance()->get();

        $redis         = new RedisPackage();
        $clock_in_scan = $redis::get('clock_in_scan_' . $param['order_id']);
        $clock_in_auth = $redis::get('clock_in_auth_' . $param['order_id']);

        $list['scan']  = empty($clock_in_scan)?0:1;
        if (!empty($clock_in_auth)) {
            if ($clock_in_auth == 1) {
                $list['auth'] = 1;
            } else {
                $list['auth'] = 2;
            }

        } else {
            $list['auth'] = 0;
        }
        $list['time'] = date('Y-m-d H:i:s',time());
        if($list['auth']==1 || $list['auth']==2){
            $clock_in    = \db('clock_in')->where('order_id', $param['order_id'])->select();
            if (count($clock_in)==1) {
                $common->CommissionCalculation($param['order_id'], $orderModel, 1);
                db('order')->where('order_id', $param['order_id'])->update(['state' => 3, 'undetermined' => 0]);
                (new PollingModel())->Alls($param['order_id'], 2, 0, $clock_in[0]['punch_clock'], $clock_in[0]['punch_clock']);
            }
        }
        r_date($list, 200);
    }
}